package cn.itsource.ymcc.jwt;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.security.PublicKey;

public class UserContext {

    public static JSONObject getUser(String jwtToken){
        try {
            PublicKey publicKey = RsaUtils
                    .getPublicKey(FileCopyUtils
                            .copyToByteArray(UserContext.class.getClassLoader().getResourceAsStream("hrm_auth_rsa.pub")));
            Payload<PayloadData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, PayloadData.class);
            PayloadData userInfo = payload.getUserInfo();
            // 如果对象 直接转为JSONObject 那么字段名就是key,值就value
            return (JSONObject) userInfo.getLogin();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前登陆人的id
     * @param jwtToken
     * @return
     */
    public static Long getUserId(String jwtToken){
        JSONObject user = getUser(jwtToken);
        return user.getLong("id");
    }
}
